package ca.etsmtl.log430.lab3;

import java.io.PipedReader;
import java.io.PipedWriter;

public class FormatFilter extends Thread {

	// Declarations

	boolean done;

	PipedReader inputPipe = new PipedReader();
	PipedWriter outputPipe = new PipedWriter();

	public FormatFilter(PipedWriter inputPipe, PipedWriter outputPipe) {

		try {

			// Connect inputPipe
			this.inputPipe.connect(inputPipe);
			System.out.println("FormatFilter:: connected to upstream filter.");

			// Connect OutputPipes

			this.outputPipe = outputPipe;
			System.out.println("FormatFilter:: connected to downstream filter.");

		} catch (Exception Error) {

			System.out.println("FormatFilter:: Error connecting to other filters.");

		} // try/catch

	} // Constructor

	// This is the method that is called when the thread is started

	public void run() {

		// Declarations

		char[] characterValue = new char[1];
		// char array is required to turn char into a string
		String lineOfText = "";
		// string is required to look for the status code
		int integerCharacter; // the integer value read from the pipe

		String[] line;
		String outputLine = "";

		try {

			done = false;

			while (!done) {

				integerCharacter = inputPipe.read();
				characterValue[0] = (char) integerCharacter;

				if (integerCharacter == -1) { // pipe is closed

					done = true;

				} else {

					if (integerCharacter == '\n') { // end of line

						if(lineOfText.length() > 0 ) {
							line = lineOfText.split(" ");
							
							// REQ001
							//Changez le format des données de sortie de telle sorte qu'elles ne comprennent que les champs 
							//suivants (dans cet ordre): Statut, État, Taux, Numéro projet. 

							outputLine = line[1] + " " + line[5] + " " + line[4] + " " + line[0] + "\n";

							System.out.println("FormatFilter:: new output is: " + outputLine);
							
							outputPipe.write(outputLine, 0, outputLine.length());
							outputPipe.flush(); 
						}

						lineOfText = "";
					} else {

						lineOfText += new String(characterValue);

					} // if //

				} // if

			} // while

		} catch (Exception error) {

			System.out.println("FormatFilter:: Interrupted.");

		} // try/catch

		try {

			inputPipe.close();
			System.out.println("FormatFilter:: input pipe closed.");

			outputPipe.close();
			System.out.println("FormatFilter:: output pipe closed.");

		} catch (Exception Error) {

			System.out.println("FormatFilter:: Error closing pipes.");

		} // try/catch

	} // run

} // class